<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>


  <script>
   /* 
  使用构造函数和ES6的类设计并测试以下需要
    需求1: 
      现在2个人, 都有姓名与年龄(值自己指定), 都能自我介绍自己的姓名和年龄, 能得到当前的总人数
    需求2: 
      现在又有了一个学生, 它有身价的属性, 能介绍它的所有信息
      又有一个老师, 它有教授课程的属性, 能介绍它的所有信息
  */

  function Person(name, age) {
    this.name = name
    this.age = age
  }

  Person.prototype.sayInfo = function () {
    console.log(`name is ${this.name}, age is ${this.age}`)
  }

  // const p1 = new Person('tom', 20)
  // const p2 = new Person('jack', 21)
  // console.log(p1.name, p1.age)
  // p1.sayInfo()

  function Student(name, age, price) {
    // this.name = name
    // this.age = age
    /* 借用父类型构造函数 */
    Person.call(this, name, age) // 相当于: this.Person(name, age)  简化编码

    this.price = price
    Student.prototype.count++
  }
  /* 让子类的原型为父类的实例 */
  Student.prototype = new Person()
  /* 让子类型原型的构造器为子类型 */
  Student.prototype.constructor = Student

  Student.prototype.count = 0


  const s1 = new Student('Bob', 23, 13000)
  console.log(s1.name, s1.age, s1.price)
  s1.sayInfo()
  console.log(s1)
  console.log(s1.constructor) // Student
  console.log(s1.count) // 1
  const s2 = new Student('Bob2', 23, 13000)
  console.log(s1.count, s2.count) // 2


  /* 
  ***方式一: 基于构造函数的继承: 原型链 + 借用构造函数的组合式继承***
  - ***借用父类型构造函数: Person.call(this, name, age)***
  - ***让子类的原型为父类的实例: Student.prototype = new Person()***
  - ***让子类型原型的构造器为子类型: Student.prototype.constructor = Student***
  */


  /* 使用class实现继承 */

  class Person2 {
    constructor (name, age) {
      this.name = name
      this.age = age
    }

    sayHello () {
      console.log(this.name, this.age)
    }
  }

  class Teacher extends Person2 {
    constructor (name, age, course) {
      super(name, age)
      this.course = course
      Teacher.prototype.count++
    }
    // 重写方法: 重新定义从父类型继承来的方法
    sayHello () {
      console.log('介绍', this.name, this.age, this.course)
    }
  }

  Teacher.prototype.count = 0

  const t1 = new Teacher('AA', 30, 'IT')
  console.log(t1.name, t1.age, t1.course)
  t1.sayHello()

  const t2 = new Teacher('AA22', 30, 'IT')
  console.log(t2.count, t1.count)
    
  </script>
  
</body>
</html>